import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/common/theme/dimens.dart';
import 'package:flutter_taotaoshipin/http/dao/user_dao.dart';
import 'package:flutter_taotaoshipin/pages/login/login_routes.dart';
import 'package:flutter_taotaoshipin/util/image_utils.dart';
import 'package:flutter_taotaoshipin/util/other_utils.dart';
import 'package:flutter_taotaoshipin/widget/gaps.dart';
import 'package:flutter_taotaoshipin/widget/my_app_bar.dart';
import 'package:flutter_taotaoshipin/widget/my_scroll_view.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:easy_stepper/easy_stepper.dart';
import 'package:hi_net/core/hi_error.dart';

class LogoutAccountPage extends StatefulWidget {
  const LogoutAccountPage({Key? key}) : super(key: key);

  @override
  State<LogoutAccountPage> createState() => _LogoutAccountPageState();
}

class _LogoutAccountPageState extends State<LogoutAccountPage> {
  TextEditingController suggestionController = TextEditingController();
  FocusNode suggestionNode = FocusNode();

  int activeStep = 0;
  bool isAgree = false;

  List<String> seasonList = [
    '多余的账号',
    '账号存在安全隐患',
    '使用和体验不好',
    '不再需要了',
    '其它',
  ];
  int? radioValue = 0;

  @override
  void dispose() {
    suggestionController.dispose();
    suggestionNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(centerTitle: '注销账号'),
      body: Column(
        children: [
          EasyStepper(
            activeStep: activeStep,
            stepRadius: 20,
            showLoadingAnimation: false,
            activeStepBorderType: BorderType.normal,
            enableStepTapping: false,
            steps: [
              EasyStep(
                icon: Icon(Icons.person),
                finishIcon: Icon(Icons.check),
                title: '确认账号',
              ),
              EasyStep(
                icon: Icon(Icons.privacy_tip),
                finishIcon: Icon(Icons.check),
                title: '同意条款',
              ),
              EasyStep(
                icon: Icon(Icons.checklist_outlined),
                finishIcon: Icon(Icons.check),
                title: '注销原因',
              ),
            ],
          ),
          Expanded(
            child: IndexedStack(
              index: activeStep,
              children: [
                _buildWidgetFirst(),
                _buildWidgetSecond(),
                _buildWidgetThird(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _buildWidgetFirst() {
    return MyScrollView(
      padding: EdgeInsets.all(Dimens.gap_dp15),
      children: [
        Center(
          child: Text(
            '确认账号',
            style: TextStyle(
              fontSize: Dimens.font_sp22,
              fontWeight: FontWeight.w700,
            ),
          ),
        ),
        Gaps.vGap15,
        GetBuilder<AppController>(
          builder: (_) => Center(
            child: CircleAvatar(
              radius: 50,
              backgroundColor: Colors.transparent,
              backgroundImage: ImageUtils.getImageProvider(
                'me/avatar',
                holderImg: 'me/avatar',
              ),
            ),
          ),
        ),
        Gaps.vGap5,
        GetBuilder<AppController>(
          builder: (controller) {
            var user = '游客';
            if (controller.userinfoCenterEntity.mobile != null &&
                controller.userinfoCenterEntity.mobile!.isNotEmpty) {
              user =
                  TextUtil.hideNumber(controller.userinfoCenterEntity.mobile!);
            }
            return Center(
              child: Text(
                user,
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.black,
                ),
              ),
            );
          },
        ),
        Gaps.vGap5,
        GetBuilder<AppController>(
          builder: (_) => Center(
            child: Text(
              'UID：${_.userinfoCenterEntity.id ?? 0}',
              style: const TextStyle(
                fontSize: 14,
                color: Colors.black,
              ),
            ),
          ),
        ),
        Gaps.vGap15,
        Center(
          child: ElevatedButton(
            onPressed: () {
              setState(() {
                activeStep = 1;
              });
            },
            child: Text(
              '确认并继续',
              style: TextStyle(fontSize: Dimens.font_sp16),
            ),
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30)),
              padding: EdgeInsets.symmetric(
                  horizontal: Dimens.gap_dp32, vertical: Dimens.gap_dp10),
            ),
          ),
        ),
      ],
    );
  }

  _buildWidgetSecond() {
    return MyScrollView(
      padding: EdgeInsets.all(Dimens.gap_dp15),
      children: [
        RichText(
          text: TextSpan(
            children: [
              WidgetSpan(
                child: Icon(
                  Icons.warning_rounded,
                  color: Colors.red,
                  size: Dimens.font_sp18,
                ),
              ),
              TextSpan(
                text: '注意：账号一旦注销后，无法找回，请您备份好账号下所以业务信息后谨慎操作。',
                style: TextStyle(color: Colors.red),
              ),
            ],
          ),
        ),
        Gaps.vGap15,
        Text(
          '账号注销，你已经了解了以下账户注销条款：',
          style: TextStyle(
            fontSize: Dimens.font_sp18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Gaps.vGap8,
        Text('1、注销账号是不可恢复的操作，你应自行备份账号的信息和数据；'),
        Gaps.vGap8,
        Text('2、注销账号前，已结清账户支付财产，账号上没有资金问题待结算；'),
        Gaps.vGap8,
        Text('3、注销账号前，请确认该账号相关的所有服务均已进行妥善处理；'),
        Gaps.vGap8,
        Text('4、注销账号为自愿放弃本账号在平台上的利益；'),
        Gaps.vGap8,
        Text('5、注销账号操作为个人自愿行为，并未受到其它因素的影响。'),
        Gaps.vGap16,
        GestureDetector(
          onTap: () {
            setState(() {
              isAgree = !isAgree;
            });
          },
          child: Row(
            children: [
              Icon(
                isAgree
                    ? Icons.check_box_rounded
                    : Icons.check_box_outline_blank_rounded,
                size: Dimens.gap_dp16,
              ),
              Text(
                ' 我已阅读并同意以上内容',
                style: TextStyle(fontSize: Dimens.font_sp16),
              ),
            ],
          ),
        ),
        Gaps.vGap50,
        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: () {
              if (!isAgree) {
                EasyLoading.showToast('请勾选同意注销条款');
                return;
              }
              setState(() {
                activeStep = 2;
              });
            },
            child: Text(
              '确认并继续',
              style: TextStyle(fontSize: Dimens.font_sp16),
            ),
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30)),
              padding: EdgeInsets.symmetric(
                  horizontal: Dimens.gap_dp32, vertical: Dimens.gap_dp10),
            ),
          ),
        ),
      ],
    );
  }

  _buildWidgetThird() {
    return MyScrollView(
      padding: EdgeInsets.all(Dimens.gap_dp15),
      keyboardConfig:
      OtherUtils.getKeyboardActionsConfig(context, [suggestionNode]),
      children: [
        Text(
          '告诉我们，您的注销原因：',
          style: TextStyle(
            fontSize: Dimens.font_sp18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Gaps.vGap8,
        ...List.generate(seasonList.length, _radioItem).toList(),
        Gaps.vGap8,
        Text(
          '您的建议：',
          style: TextStyle(
            fontSize: Dimens.font_sp18,
            fontWeight: FontWeight.bold,
          ),
        ),
        Gaps.vGap8,
        TextField(
          controller: suggestionController,
          focusNode: suggestionNode,
          keyboardType: TextInputType.multiline,
          maxLines: 5,
          decoration: InputDecoration(
            hintText: '内容',
            contentPadding: EdgeInsets.symmetric(
              horizontal: Dimens.gap_dp10,
              vertical: Dimens.gap_dp5,
            ),
            border: OutlineInputBorder(),
          ),
        ),
        Gaps.vGap50,
        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: () {
              _loadUserCancelData();
            },
            child: Text(
              '提交注销原因',
              style: TextStyle(fontSize: Dimens.font_sp16),
            ),
            style: ElevatedButton.styleFrom(
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30)),
              padding: EdgeInsets.symmetric(
                  horizontal: Dimens.gap_dp32, vertical: Dimens.gap_dp10),
            ),
          ),
        ),
      ],
    );
  }

  _radioItem(int index) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(seasonList[index]),
        Radio(
          value: index,
          groupValue: radioValue,
          onChanged: (value) {
            setState(() {
              radioValue = value;
            });
          },
        ),
      ],
    );
  }

  /// 注销用户
  Future<void> _loadUserCancelData() async {
    var errorMsg = '注销失败';
    try {
      EasyLoading.show();
      var result = await UserDao.cancel();
      if (result.code == 0) {
        // 请求结果成功，数据不为空
        if (result.data != null) {
          if(result.data!.state == 1) {
            EasyLoading.showSuccess('注销成功');
            // 跳转登录页
            Get.offAllNamed(LoginRoutes.phoneLogin, arguments: {'type': 1});
            return;
          }
        }
      }
    } on HiNetError catch (e) {
      errorMsg = e.message;
    } catch (e) {
      print(e.toString());
    }
    EasyLoading.showError(errorMsg);
  }
}
